<template>
    <div>
        <el-form size="small" label-width="90px">
          <el-button type="primary" @click="openImageList">选择图片</el-button>
        </el-form>
        
        <el-dialog title="图片列表" :visible.sync="dialogVisible" :close-on-click-modal="false" height="500px">
            <div style="overflow:auto; height:300px;">
              <ul
                  class="background-images-ul"
                  v-infinite-scroll="load"
                  infinite-scroll-disabled="disabled">
                  <div class="icon_plus" @click="openImageGallary"><i class="el-icon-circle-plus" style="font-size:45px"/></div>
                  <li v-for="item in fileList" style="overflow:hidden">
                    <img :src="basePath + item.imagePath" class="border_img">
                    <span title="删除" class="drawing-item-delete" @click.stop="removeImageList(item)"><i class="el-icon-delete"></i></span>
                  </li>
              </ul>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitImage">确定</el-button>
                <el-button @click="cancelList">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 图库对话框 -->
        <el-dialog title="图库" :visible.sync="open" width="1000px" height="600px" append-to-body>
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="所属模板">
            <el-input
                v-model="queryParams.viewTemplate"
                placeholder="请输入所属模板"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
            </el-form-item>
            
            <el-form-item label="图片分类" prop="status">
            <el-select
                v-model="queryParams.sort"
                placeholder="图片分类"
                clearable
                size="small"
                style="width: 240px"
            >
                <el-option
                v-for="item in sortOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                />
            </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="uploadOpenModel">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            </el-form-item>
          </el-form>

          <div style="overflow:auto; height:500px;">
            <ul
                class="background-images-ul"
                v-infinite-scroll="load"
                infinite-scroll-disabled="disabled">
                <li v-for="item in uploadList" @click="addImageList(item)" style="overflow:hidden">
                  <span title="已选择" :style='itemCheck(item)'><i class="el-icon-success"/></span>
                  <img :src="basePath + item.imagePath" class="border_img">
                  <label :title="item.name">{{ item.name }}</label>
                  <span title="删除" class="drawing-item-delete" @click.stop="deleteImage(item.uploadId)"><i class="el-icon-delete"></i></span>
                </li>
            </ul>
            <p v-if="loading" style="text-align: center;">加载中...</p>
            <p v-if="noMore" style="text-align: center;">没有更多了</p>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="cancel">确定</el-button>
          </div>
        </el-dialog>

        <!-- 添加或修改数据大屏文件上传映射对话框 -->
        <el-dialog title="上传图片" :visible.sync="uploadOpen" width="500px" append-to-body>
          <el-form ref="uploadForm" :model="uploadForm" :rules="rules"  label-width="80px">

            <el-form-item label="是否公开" prop="isOpen">
                <el-radio-group v-model="uploadForm.isOpen">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="是否模板素材" prop="isTemplate" v-if="adminRole">
                <el-radio-group v-model="uploadForm.isTemplate">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
                </el-radio-group>
            </el-form-item>            
            
            <el-form-item label="所属模板" prop="viewTemplate">
              <el-input v-model="uploadForm.viewTemplate" style="width: 360px" placeholder="请输入所属模板" />
            </el-form-item>

            <el-form-item label="图片分类" prop="sort">
                <el-select
                v-model="uploadForm.sort"
                placeholder="图片分类"
                clearable
                size="small"
                style="width: 360px"
            >
                <el-option
                v-for="item in sortOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                />
            </el-select>
            </el-form-item>
            
            <el-form-item label="上传">
                <el-upload
                class="upload-demo"
                drag
                action
                :on-remove="handleRemove"
                :http-request="httpRequest"
                :file-list="showFileList"
                :show-file-list="true" :before-upload="beforeUpload"
                multiple>
                <i class="el-icon-upload"></i>
                </el-upload>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitUpload">提交</el-button>
            <el-button @click="cancelUpload">取 消</el-button>
          </div>
        </el-dialog>

    </div>
</template>

<script>
import { listUpload, fileUpload, delUpload } from "@/api/tool/datav/fileUpload";
  export default {
    props:["imageList"],
    data() {
      
      return {
        dialogImageUrl: '',
        fileList: this.imageList,
        dialogVisible: false,
        selectedImgs:[], //图库中选择的图片列表
        basePath: process.env.VUE_APP_BASE_API,
        open: false,
        sortOptions: [{label:'图标', value: 1}, {label:'边框', value: 2}, {label:'按钮', value: 3}],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          type: '1',
          sort: undefined,
          viewTemplate: undefined,
        },
        rules: {
          isOpen: [
            { required: true, message: "是否公开不能为空", trigger: "blur" }
          ],
          sort: [
            { required: true, message: "所属分类不能为空", trigger: "blur" }
          ]
        },
        uploadList: [],//查询文件列表
        total: -1,
        loading: false,
        uploadOpen: false,
        uploadForm: {
          isOpen:"0",
          isTemplate:"0"
        },
        showFileList:[],//上传后展示文件列表
        adminRole: false,//管理员权限
      };
    },
    watch:{
      imageList:{
        deep:true,
        immediate:true,
        handler(val){
          this.fileList = val
        }
      }
    },
    computed: {
      noMore () {
        if(this.total != -1) {
          return this.total == this.uploadList.length
        } else {
          return false;
        }
      },
      disabled () {
        return this.loading || this.noMore
      },
      itemCheck(){
        return function(item){
          let style ={
            display:'none',
            
          }
          
          for(let index in this.fileList){
            if(item.uploadId == this.fileList[index].uploadId){
              style={
                width: 28+'px',
                height: 28+'px',
                position:'absolute',
                color: 'rgb(57, 126, 255)',
                top:0,
                left:0,
              }
            }
          }
          return style
        }
      }
    },
    created() {
      let roles = this.$store.getters.roles;
      let result = roles.find(ele => ele === 'admin')//判断是否包含admin权限
      if (result) {
        this.adminRole = true;
      };
    },    
    methods: {
      removeImageList(item) {
        for(let index in this.fileList){
            if(item.uploadId == this.fileList[index].uploadId){
                this.fileList.splice(index, 1)
            }
        }
      },
      openImageList(){
        this.dialogVisible=true
      },
      openImageGallary(){
        this.open = true;
      },
      submitImage(){
        // this.$emit("getImgList", this.fileList);
        this.dialogVisible = false
      },
      cancelList(){
        this.open = false;
        this.dialogVisible = false
      },
      cancel(){
          this.open = false;
      },
      handleQuery() {
        this.total = -1;
        this.uploadList = [];
        this.queryParams.pageNum = 1;
        this.open = true;
        this.load();
      },
      load () {
        this.loading = true;
        listUpload(this.queryParams).then(response => {
          this.uploadList = this.uploadList.concat(response.rows);
          this.total = response.total;
          this.queryParams.pageNum++;
          this.loading = false;
        });
      },
      selectImg(item) {
        this.$emit("getImg", this.basePath +item); 
        this.open = false;
      },
      // 上传预处理
      beforeUpload(file) {
        if (file.type.indexOf("image/") == -1) {
          this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        }
      },
      //取消上传
      cancelUpload() {
          this.uploadOpen = false;
          this.showFileList = []
      },
      uploadOpenModel() {
          this.uploadOpen = true;
      },
      //删除预处理
      handleRemove(file, fileList) {
        //在已上传文件列表中删除选中图片
          this.showFileList.forEach((it, index) => {
              if(it.file.name == file.name){
                this.showFileList.splice(index,1)
              }
            });
        },
      //自定义上传,重写文件上传方法,覆盖原有的上传方法，将上传的文件依次添加到showFileList数组中
      httpRequest(option) {
          option.name = option.file.name
          this.showFileList.push(option);
          this.msgSuccess("成功上传至浏览器缓存");
      },
      submitUpload() {
        this.$refs["uploadForm"].validate(valid => {
          if (valid) {
              // 使用form表单的数据格式
            let paramsData = new FormData()
            // 将上传文件数组依次添加到参数paramsData中
            this.showFileList.forEach((it, index) => {
              paramsData.append('file', it.file); // 因为要上传多个文件，所以需要遍历一下才行
            });
            // 将表单数据添加到参数paramsData中
            paramsData.append('isOpen', this.uploadForm.isOpen)
            paramsData.append('isTemplate', this.uploadForm.isTemplate)
            paramsData.append('viewTemplate', this.uploadForm.viewTemplate)
            paramsData.append('sort', this.uploadForm.sort)
            paramsData.append('type', '1')
            // 表单数据和文件一起上传,调用后端接口
            fileUpload(paramsData).then(response => {
              if (response.code == 200) {
                  this.uploadOpen = false;
                  this.showFileList = [];
                  this.uploadForm.isOpen = "0";
                  this.uploadForm.isTemplate = "0";
                  this.uploadForm.viewTemplate = undefined;
                  this.uploadForm.sort = undefined;
                  this.msgSuccess("上传成功");
                  //重新加载上传数据
                  this.uploadList = [];
                  this.queryParams.pageNum = 1;
                  this.load();
              }
            });
          
          }
        });
      },
      deleteImage(uploadId){
        this.$confirm('是否确认删除该图片?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delUpload(uploadId).then(response => {
          if (response.code === 200) {

            this.msgSuccess("删除成功");
              //重新加载上传数据
              this.uploadList = [];
              this.queryParams.pageNum = 1;
              this.load();
          } else {
            this.msgError(response.msg);
          }
        });
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除操作'
          });          
        });
      },
      pageCount (totalnum, limit) {
          return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0;
      },
      addImageList(item){
        let flag = false
        for(let index in this.fileList){
            if(item.uploadId == this.fileList[index].uploadId){
                flag = true
                this.fileList.splice(index, 1)
            }
        }
        if(!flag){
          this.fileList.push(item)
        }
      },
    },
  }
</script>

<style lang='scss'  scoped>
.background-images-ul {
    margin-bottom: 20px;
}
.background-images-ul li {
    margin: 2px;
    display: inline-block;
    width: 200px;
    line-height: 25px;
    padding: 20px;
    border: 1px solid #e2e2e2;
    font-size: 14px;
    text-align: center;
    color: #666;
    transition: all .3s;
    -webkit-transition: all .3s;
    cursor: pointer;
    position: relative;
    &:hover {
      
      & > .drawing-item-delete{
        display: initial;
      }
    }
    & > .drawing-item-copy, & > .drawing-item-delete{
      display: none;
      position: absolute;
      top: 0px;
      right: 15px;
      width: 22px;
      height: 22px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      font-size: 12px;
      border: 1px solid;
      cursor: pointer;
      z-index: 1;
   }
    & > .drawing-item-delete{
      right: 0px;
      border-color: #F56C6C;
      color: #F56C6C;
      background: #fff;
      &:hover{
        background: #F56C6C;
        color: #fff;
      }
  }
}
.border_img {
    width: 120px;
    height: 120px;
    object-fit: contain;
}
.icon_plus {
    display:inline-block;
    margin: 2px;
    width: 200px;
    height: 169px;
    padding-top: 55px;
    border: 2px dashed #7c7c7c;
    border-radius: 6px;
    vertical-align:top;
    text-align: center;
}
.background-images-ul label {
    display: inline;
    width: 160px;
    color: #DBEEFF;
    overflow: hidden;
}
.background-images-ul label{
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>